package com.zhangyj.util;

import java.sql.SQLException;
import java.util.Iterator;
import java.util.List;

import com.zhangyj.entitis.TreeItem;

public class OutlookBarCreator {
	private String contextPath;
	private List<TreeItem> milist;

	public OutlookBarCreator(List<TreeItem> list, String contextPath) {
		this.contextPath = null;
		milist = list;
		this.contextPath = contextPath;
		init();
	}



	private void init() {
		if (contextPath == null) {
			contextPath = "";
		}
	}

	public String getHtml() throws SQLException {
		StringBuilder buffer = new StringBuilder();
			buildHtmlFromList(buffer);
		return buffer.toString();
	}

	private void buildHtmlFromList(StringBuilder buffer) {
		String parentCode = null;
		for (Iterator<TreeItem> itr = milist.iterator(); itr.hasNext();) {
			TreeItem item= itr.next();
			int id = item.getId();
			String code = item.getCode();
			String desc = item.getDescription();
			boolean isleaf = item.isLeaf();
			if (parentCode == null) {
				parentCode = code;
				appendTitle(buffer, id, code, desc);
			} else if (code.startsWith(parentCode)) {
				appendItem(buffer, id, code, desc, isleaf);
			} else {
				parentCode = code;
				appendTail(buffer);
				appendTitle(buffer, id, code, desc);
			}
		}

		if (parentCode != null) {
			appendTail(buffer);
		}
	}
	private void appendTitle(StringBuilder buffer, int id, String code, String desc) {
		buffer.append("<div><div class=\"bartitle\">");
		buffer.append("<table  valign=\"center\">");
		buffer.append("<tr><td class=\"outlookbartitle\" title=\"").append(desc).append("\" valign=\"center\">");
		buffer.append(desc);
		buffer.append("</td><td width=\"11px\" valign=\"center\">");
		buffer.append("<img src=\"");
		buffer.append(contextPath);
		buffer.append("/common/images/outlookup.gif\" align=\"right\" valign=\"top\"/></td></tr></table></div>");
		buffer.append("<div class=\"baritem\"><span><ul class=\"listItem\">");
	}

	private void appendItem(StringBuilder buffer, int id, String code, String desc, boolean isleaf) {
		if (isleaf) {
			buffer.append("<li title=\"").append(desc).append(
					"\" onmouseover=\"this.className='listMoveItem'\" onmouseout=\"this.className=''\" uid=\"").append(id).append("\" ")
					.append("ucode=\"").append(code).append("\">");
		} else {
			buffer.append("<li class='lidisabled'>");
		}
		buffer.append(desc);
		buffer.append("</li>");
	}

	private void appendTail(StringBuilder buffer) {
		buffer.append("</ul></span></div></div>");
	}


}
